<template>
  <!-- <div class='container'>基础题库</div> -->
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 新增试题 -->
        <div style="text-align: right; height: 50px">
          <el-button
            size="small"
            type="success"
            @click="hAdd"
            icon="el-icon-edit">
            新增试题
          </el-button>
        </div>
        <!-- 表单区域 -->
        <el-form :model="form" ref="form" label-width="100px" label-position="right">
          <el-row :gutter="10">
            <!-- 学科 -->
            <el-col :span="6">
              <el-form-item label="学科" prop="subject">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  @change="hCatalogs"
                  v-model="form.subject">
                  <el-option
                    v-for="item in formList.subjectList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 二级目录 -->
            <el-col :span="6">
              <el-form-item label="二级目录" prop="catalog">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.catalog">
                  <el-option
                    v-for="item in formList.catalogList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 标签 -->
            <el-col :span="6">
              <el-form-item label="标签" prop="tag">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.tag">
                  <el-option
                    v-for="item in formList.tagList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 关键字 -->
            <el-col :span="6">
              <el-form-item label="关键字" prop="keyword">
                <el-input
                  size="small"
                  placeholder="根据题干搜索"
                  v-model="form.keyword">
                </el-input>
              </el-form-item>
            </el-col>
            <!-- 试题类型 -->
            <el-col :span="6">
              <el-form-item label="试题类型" prop="questionType">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.questionType">
                  <el-option
                    v-for="item in formList.questionTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 难度 -->
            <el-col :span="6">
              <el-form-item label="难度" prop="difficulty">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.difficulty">
                  <el-option
                    v-for="item in formList.difficultyList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 方向 -->
            <el-col :span="6">
              <el-form-item label="方向" prop="direction">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.direction">
                  <el-option
                    v-for="(item, i) in formList.directionList"
                    :key="i"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 录入人 -->
            <el-col :span="6">
              <el-form-item label="录入人" prop="author">
                <el-select
                  clearable
                  size="small"
                  placeholder="请选择"
                  v-model="form.author">
                  <el-option
                    v-for="(item, i) in formList.authorList"
                    :key="i"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 题目备注 -->
            <el-col :span="6">
              <el-form-item label="题目备注" prop="remarks">
                <el-input
                  size="small"
                  v-model="form.remarks">
                </el-input>
              </el-form-item>
            </el-col>
            <!-- 企业简称 -->
            <el-col :span="6">
              <el-form-item label="企业简称" prop="abbreviation">
                <el-input
                  size="small"
                  v-model="form.abbreviation">
                </el-input>
              </el-form-item>
            </el-col>
            <!-- 城市 -->
            <el-col :span="6">
              <el-form-item label="城市" size="small">
                <my-city v-model="form.provAndCity"></my-city>
              </el-form-item>
            </el-col>
            <!-- 清除和搜索两个按钮 -->
            <el-col :span="6" style="text-align: right">
              <el-button @click="hResetForm" size="small" plain>清除</el-button>
              <el-button @click="hSearch" size="small" type="primary">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
        <!-- 表格数据统计 -->
        <el-alert
          type="info"
          show-icon>
          <span>根据条件找到了{{myPage.counts}}条数据</span>
        </el-alert>
        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          style="width: 100%">
          <el-table-column
            prop="id"
            label="试题编号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="subject"
            label="学科"
            width="100">
          </el-table-column>
          <el-table-column
            prop="catalog"
            label="目录"
            width="100">
          </el-table-column>
          <el-table-column
            label="题型"
            width="100">
            <template slot-scope="scope">
              {{scope.row.questionType | fQuesTypeText}}
            </template>
          </el-table-column>
          <el-table-column
            label="题干">
            <template slot-scope="scope">
             {{scope.row.question | fQuestion}}
            </template>
          </el-table-column>
          <el-table-column
            prop="addDate"
            :formatter="formData"
            label="录入时间"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.addDate | parseTimeByString("{y}-{m}-{d} {h}:{i}:{s}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="难度"
            width="100">
            <template slot-scope="scope">
              {{scope.row.questionType | fDifficultyText}}
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="录入人"
            width="100">
          </el-table-column>
          <el-table-column
            label="操作"
            width="180">
            <template slot-scope="scope">
              <el-button @click="hPreview(scope.row.id)" size="mini" plain type="primary" icon="el-icon-view" circle></el-button>
              <el-button @click="hEdit(scope.row.id)" size="mini" plain type="success" icon="el-icon-edit" circle></el-button>
              <el-button @click="hDelete(scope.row)" size="mini" plain type="danger" icon="el-icon-delete" circle></el-button>
              <el-button @click="hCollect(scope.row)" size="mini" plain type="warning" icon="el-icon-check" circle></el-button>
            </template>
          </el-table-column>
        </el-table>
          <!-- //题目预览 -->
        <el-dialog title="题目预览" :visible.sync="dialogFormVisible">
            <QuestionsPreview :id="curid" @close="hClose" v-if="dialogFormVisible"></QuestionsPreview>
          </el-dialog>

        <!-- 分页 -->
        <el-pagination
          class="el-pagination"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="myPage.currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="myPage.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="myPage.counts">
        </el-pagination>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as getSubjectList } from '@/api/hmmm/subjects'
import { simple as getCatalogs } from '@/api/hmmm/directorys'
import { simple as getTags } from '@/api/hmmm/tags'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { list as getQuestionList, remove, choiceAdd } from '@/api/hmmm/questions'
import { parseTime } from '@/filters/index'
import MyCity from './companys/citys'
import QuestionsPreview from '../components/questions-preview'
export default {
  name: 'Questions',
  components: {
    MyCity,
    QuestionsPreview // 试题预览
  },
  data () {
    return {
      form: {
        subject: '',
        catalog: '',
        tag: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '', // 用户选中的方向
        author: '',
        remarks: '',
        abbreviation: '',
        provAndCity: { // 城市
          province: '',
          city: ''
        }
      },
      formList: {
        subjectList: [],
        catalogList: [],
        tagList: [],
        questionTypeList: questionType,
        difficultyList: difficulty,
        directionList: direction, // 系统中提供的所有的方向列表
        authorList: ['超级管理员', '录入管理员']
      },
      tableData: [], // 列表表格信息
      dialogFormVisible: false,
      myPage: {
        currentPage: 1,
        page: 1,
        pageSize: 5,
        total: 1,
        counts: 10
      }
    }
  },
  created () {
    this.loadForm()
    this.loadQuestions()
  },
  filters: {
    // 题型数字转换
    fQuesTypeText (status) {
      const texts = {
        1: '单选',
        2: '多选',
        3: '简答'
      }
      return texts[status]
    },
    // 难度数字转换
    fDifficultyText (status) {
      const texts = {
        1: '简单',
        2: '一般',
        3: '困难'
      }
      return texts[status]
    },
    // 过滤所有标签
    fQuestion (question) {
      return question.replace(/<.*?>/ig, '')
    }
  },
  methods: {
    async loadForm () {
      // 获取学科
      const subjects = await getSubjectList()
      try {
        this.formList.subjectList = subjects.data
      } catch (err) {}
    },
    async hCatalogs (e) {
      // 学科下的二级目录
      // console.log(e) // e就是选中的学科id
      try {
        const catalogs = await getCatalogs({ subjectID: e })
        this.formList.catalogList = catalogs.data
      } catch (err) {}
      try {
        // 学科下的标签
        const tags = await getTags({ subjectID: e })
        this.formList.tagList = tags.data
      } catch (err) {}
    },
    // 新增试题按钮
    hAdd () {
      this.$router.push('/questions/new')
    },
    // 重置整个表单
    hResetForm () {
      // el 表单组件上有一个resetFields方法
      this.$refs.form.resetFields()
      // 由于provAndCity传给了自定义组件，它们并不是在当前表单中直接
      // 使用的，所以，这里要去做手动清空
      this.form.provAndCity.province = ''
      this.form.provAndCity.city = ''
    },
    // 搜索试题
    async hSearch () {
      try {
        // 第一次写的
        // 重置页码
        this.myPage.page = 1
        // 重发请求
        this.loadQuestions()
      } catch (err) {}
    },
    // 组建请求参数
    buildParams () {
      const paramsObj = {}
      const { subject, catalog, tag, keyword, questionType, difficulty, direction, author, remarks, abbreviation, provAndCity } = this.form
      const { page, pageSize } = this.myPage
      // 如果某一个参数是null,则axios就不会发这个参数
      // 如果某一个参数是""，axios是会发出这个参数
      paramsObj.page = page || null
      paramsObj.pagesize = pageSize || null
      paramsObj.subjectID = subject || null
      paramsObj.difficulty = difficulty || null
      paramsObj.questionType = questionType || null
      paramsObj.tags = tag || null
      paramsObj.city = provAndCity.city || null
      paramsObj.province = provAndCity.province || null
      paramsObj.keyword = keyword || null
      paramsObj.remarks = remarks || null
      paramsObj.shortName = abbreviation || null
      paramsObj.direction = direction || null
      paramsObj.creatorID = author || null
      paramsObj.catalogID = catalog || null
      return paramsObj
    },
    // 获取表格数据
    async loadQuestions () {
      try {
        const params = this.buildParams()
        const res = await getQuestionList(params)
        // console.log(res)
        const { items, counts } = res.data
        this.tableData = items
        this.myPage.counts = counts
      } catch (err) {}
    },
    // 时间格式化
    formData (row) {
      // console.log(row.addDate)
      return parseTime(row.addDate, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    // 预览试题
    async hPreview (id) {
      // 此处要控制插件
      this.curid = id
      this.dialogFormVisible = true
    },
    // 关闭弹窗按钮
    hClose (value) {
      console.log(value)
      this.dialogFormVisible = value
    },
    // 编辑试题
    hEdit (e) {
      this.$router.push({
        path: '/questions/new',
        query: {
          id: e
        }
      })
    },
    // 删除试题
    hDelete (row) {
      this.$confirm('确定要删除本题吗？').then(() => {
        this.doDelete(row)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.error('删除失败')
      })
    },
    async doDelete (row) {
      await remove({ id: row.id })
      this.loadQuestions()
    },
    // 收藏试题
    async hCollect (row) {
      this.$confirm('需要加入精选题库吗？').then(async () => {
        await choiceAdd({
          id: row.id,
          choiceState: 1
        })
        this.$message.success('精选成功')
        // 重新铺设页面
        this.loadQuestions()
      }).catch(() => {
        this.$message.error('精选失败')
      })
    },
    // 分页
    // 更改每页显示的条数
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`);
      this.myPage.pageSize = val
      this.loadQuestions()
    },
    // 显示第几页
    handleCurrentChange (curPage) {
      // console.log('现在要显示', curPage)
      this.myPage.page = curPage
      this.loadQuestions()
    }
  }
}

</script>

<style scoped rel="stylesheet/scss" lang="scss">
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
